package com.atguigu.gmall.pms.service.impl;

import com.atguigu.gmall.pms.entity.*;
import com.atguigu.gmall.pms.feign.GmallSmsClient;
import com.atguigu.gmall.pms.mapper.SkuMapper;
import com.atguigu.gmall.pms.mapper.SpuDescMapper;
import com.atguigu.gmall.pms.service.SkuAttrValueService;
import com.atguigu.gmall.pms.service.SkuImagesService;
import com.atguigu.gmall.pms.service.SpuAttrValueService;
import com.atguigu.gmall.pms.vo.SkuVo;
import com.atguigu.gmall.pms.vo.SpuAttrValueVo;
import com.atguigu.gmall.pms.vo.SpuVo;
import com.atguigu.gmall.sms.vo.SkuSaleVo;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.pms.mapper.SpuMapper;
import com.atguigu.gmall.pms.service.SpuService;
import org.springframework.util.CollectionUtils;


@Service("spuService")
public class SpuServiceImpl extends ServiceImpl<SpuMapper, SpuEntity> implements SpuService {

    @Autowired
    private SpuService spuService;
    @Autowired
    private SpuDescMapper spuDescMapper;
    @Autowired
    private SpuAttrValueService spuAttrValueService;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuAttrValueService skuAttrValueService;
    @Autowired
    private GmallSmsClient smsClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<SpuEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<SpuEntity>()
        );

        return new PageResultVo(page);
    }

    @Override
    public PageResultVo queryCategoryPage(Long categoryId, PageParamVo pageParamVo) {

       QueryWrapper<SpuEntity> queryWrapper=new QueryWrapper<SpuEntity>(  );
       // 添加分页查询条件
       if (categoryId !=0){
           queryWrapper.eq( "category_id",categoryId );
       }
       // categoryId加关键字查询
        String key = pageParamVo.getKey();
       //if(key !=null && key.trim().length()>0){}
       if (StringUtils.isNotBlank( key )){
           queryWrapper.and( t -> t.eq( "id" ,key ).or().like( "name" ,key));
       }
        IPage<SpuEntity> page = this.page(
                pageParamVo.getPage(),
                queryWrapper
        );

        return new PageResultVo(page);
    }

    @Override
    @GlobalTransactional
    public void bigSave(SpuVo spu) {
        //关联九张表的保存数据
        //1.保存spu相关的信息
        //1.1 pms_spu
        spu.setCreateTime( new Date(  ) );
        spu.setUpdateTime( spu.getCreateTime() );
        this.spuService.save( spu );
        Long spuId= spu.getId();
        //1.2 pms_spu_desc
        List<String> spuImages = spu.getSpuImages();
        if (!CollectionUtils.isEmpty( spuImages )){
            SpuDescEntity spuDescEntity=new SpuDescEntity();
            spuDescEntity.setSpuId( spuId );
            spuDescEntity.setDecript( StringUtils.join( spuImages,"," ) );
            this.spuDescMapper.insert( spuDescEntity );
        }
        //1.3 pms_spu_attr_value
        List<SpuAttrValueVo> baseAttrs = spu.getBaseAttrs();
        // 把vo集合转换成entity集合,然后批量保存到数据库
        if (!CollectionUtils.isEmpty( baseAttrs )){
            List<SpuAttrValueEntity> spuAttrValueEntityCollect = baseAttrs.stream().map( spuAttrValueVo -> {
                SpuAttrValueEntity spuAttrValueEntity = new SpuAttrValueEntity();
                // 集合复制工具类BeanUtils
                BeanUtils.copyProperties( spuAttrValueVo, spuAttrValueEntity);
                spuAttrValueEntity.setSpuId( spuId );
                return spuAttrValueEntity;
            } ).collect( Collectors.toList() );
            this.spuAttrValueService.saveBatch( spuAttrValueEntityCollect );
        }
        //2.保存sku相关信息
        // 2.1 pms_sku
        List<SkuVo> skus = spu.getSkus();
        if (CollectionUtils.isEmpty( skus )){
            return;
        }
        skus.forEach( skuVo -> {
            skuVo.setSpuId(  spuId);
            skuVo.setBrandId( spu.getBrandId() );
            skuVo.setCategoryId( spu.getCategoryId() );
            // 获取图片合集,获取默认图片
            List<String> images = skuVo.getImages();
            if (!CollectionUtils.isEmpty( images )){
                skuVo.setDefaultImage( StringUtils.isBlank(skuVo.getDefaultImage())? images.get( 0 ):skuVo.getDefaultImage());
            }
            this.skuMapper.insert( skuVo );
            Long skuId = skuVo.getId();
            // 2.2 pms_sku_images
            if (!CollectionUtils.isEmpty( images )){
                this.skuImagesService.saveBatch( images.stream().map( image -> {
                    SkuImagesEntity skuImagesEntity=new SkuImagesEntity();
                    skuImagesEntity.setSkuId(  skuId);
                    skuImagesEntity.setUrl( image );
                    // 字符串比较StringUtils.equals
                    skuImagesEntity.setDefaultStatus( StringUtils.equals( image,skuVo.getDefaultImage() )?1:0 );
                    return skuImagesEntity;
                } ).collect( Collectors.toList() ) );
            }
            // 2.3 pms_sku_attr_value
            List<SkuAttrValueEntity> saleAttrs = skuVo.getSaleAttrs();
            if (!CollectionUtils.isEmpty( saleAttrs )){
                saleAttrs.forEach( skuAttrValueEntity -> {
                    skuAttrValueEntity.setSkuId( skuId );

                } );
                this.skuAttrValueService.saveBatch( saleAttrs );
            }

            //3.保存营销的相关信息
            SkuSaleVo skuSaleVo=new SkuSaleVo();
            BeanUtils.copyProperties( skuVo,skuSaleVo );
            skuSaleVo.setSkuId(skuId);
            this.smsClient.saveSales(skuSaleVo);
        } );

        this.rabbitTemplate.convertAndSend( "pms_spu_exchange","item.insert",spuId );
    }


}